def main():
    N, M = map(int, input().split())
    grid = [[[10001]*(N+1) for _ in range(N+1)] for _ in range(N+1)]
    
    for i in range(M):
        s, t, value = map(int, input().split())
        grid[s][t][0] = value
        grid[t][s][0] = value
    
    for k in range(1, N+1):
        for i in range(1, N+1):
            for j in range(1, N+1):
                grid[i][j][k] = min(grid[i][j][k-1], grid[i][k][k-1]+grid[k][j][k-1])
    

    
    num_view = int(input())
    
    for i in range(num_view):
        start, end = map(int, input().split())
        if grid[start][end][-1] > 10000 :
            print(-1)
        else:
            print(grid[start][end][-1])

main()